package main

import (
	"fmt"
	"sync"
	"time"
)

// 任务
type Task struct {
	ID   int
	Data string
}

// 工作协程
func Worker(id int, task <-chan Task, wg *sync.WaitGroup) {
	defer wg.Done()
	for task := range task {
		fmt.Printf("Worker %d processing task %d: %s\n", id, task.ID, task.Data)
		time.Sleep(time.Second)
	}
}

func main() {
	var taskNum = 10
	//创建一个任务通道
	tasks := make(chan Task, taskNum)
	//创建一个WaitGroup等待所有协程完成
	var wg sync.WaitGroup
	//启动多个工作协程
	numWorkers := 3
	for i := 1; i < numWorkers; i++ {
		wg.Add(1)
		go Worker(i, tasks, &wg)
	}
	//添加任务到队列
	for i := 0; i < taskNum; i++ {
		tasks <- Task{ID: i, Data: fmt.Sprintf("Task data %d", i)}
	}
	close(tasks)
	wg.Wait()
	fmt.Println("All tasks processed.")
}
